package com.funny.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.funny.service.RedisService;
import com.funny.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

/**
 * @author Ming
 * @description
 * @fileSimpleName UserTestController
 * @fileName com.funny.controller.UserTestController
 * @date 2024年07月02日 18:40
 */
@Slf4j
@RestController
@RequestMapping(value = "/user")
public class UserTestController {

    @Autowired
    private RedisService redisService;

    @Autowired
    private UserService userService;

    @GetMapping("/queryUserInfoByName")
    public String queryUserInfoByName(String userName) {
        return userService.queryUserInfoByName(userName);
    }

    @GetMapping("/queryUserInfo")
    public String queryUserInfo(String userName) {
        redisService.setCacheObject("Ming","MingMing");
        return userService.queryUserInfo(userName);
    }

    /**
     * 慢调用比例
     */
    @GetMapping("/test/timeout")
    public String timeoutTest() {
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        log.info("慢调用测试!");
        return "慢调用测试!";
    }

    /**
     * 异常比例
     */
    @GetMapping("/test/exception")
    public String exceptionTest() {
        log.info("异常比例!");
        int i = 10 / 0;
        return "异常比例!";
    }

    /**
     * 热点限流
     * value 表示热点规则中的资源名
     * blockHandler 参数表示：降级方法,降级方法必须为 public,且参数和需要限流的方法一样,这样触发降级时,页面不会显示500,而是降级方法中展示出来的信息
     */
    @GetMapping("/test/hotKey")
    @SentinelResource(value = "testHotKey", blockHandler = "testHotKeyBlockHandler")
    public String testHotKey(@RequestParam(value = "key1", required = false) String key1, @RequestParam(value = "key2", required = false) String key2) {
        log.info("testHotKey!");
        return "testHotKey!";
    }


    public String testHotKeyBlockHandler(String key1, String key2, BlockException e) {
        log.info("testHotKey!");
        return "testHotKey,热点流控降级";
    }

}
